<html>
  <head>
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <meta name="theme-color" content="#008000"/>
   <title>fuzz</title>
   <!-- <link rel="manifest" href="hello_ml_manifest.json"> -->
   <style>
      body {
        margin: 0;
      }
   </style>
  </head>
  <body>
  <h1>fuzz</h1>
  <script src="three.js"></script>
  <script>
    let container, scene, camera, session, layers;

    function init() {
      container = document.createElement('div');
      document.body.appendChild(container);

      scene = new THREE.Scene();
      scene.matrixAutoUpdate = false;
      // scene.background = new THREE.Color(0x3B3961);

      camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
      // camera.position.set(0, 1, 0);
      camera.lookAt(new THREE.Vector3());
      scene.add(camera);

      const ambientLight = new THREE.AmbientLight(0x808080);
      scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
      directionalLight.position.set(1, 1, 1);
      scene.add(directionalLight);

      renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
      });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);

      // window.browser.magicleap.RequestDepthPopulation(true);
      // renderer.autoClear = false;

      container.appendChild(renderer.domElement);
      
      layers = [renderer.domElement];

      renderer.setAnimationLoop(animate);
    }

    function animate(time, frame) {
      renderer.render(scene, renderer.vr.enabled ? renderer.vr.getCamera(camera) : camera);
    }

    init();

    (async () => {
      console.log('request session');

      if (typeof FakeXRDisplay !== 'undefined') {
        const fakeXrDisplay = new FakeXRDisplay();
        fakeXrDisplay.enable();
      }

      session = await navigator.xr.requestSession({
        exclusive: true,
      }).catch(err => Promise.resolve(null));
      session.layers = layers;

      if (session) {
        // console.log('request first frame');
        session.requestAnimationFrame((timestamp, frame) => {
          renderer.vr.setSession(session, {
            frameOfReferenceType: 'stage',
          });

          const {views} = frame.getViewerPose();
          const viewport = session.baseLayer.getViewport(views[0]);
          const width = viewport.width;
          const height = viewport.height;

          renderer.setSize(width * 2, height);

          renderer.setAnimationLoop(null);

          renderer.vr.enabled = true;
          renderer.vr.setAnimationLoop(animate);

          const URL = 'https://rawcdn.githack.com/exokitxr/webxr-samples/a8e2c94eba0ee5c9215f20d13057b6c25675d9b0/xr-presentation.html';
          const _reload = () => {
            const lastIframe = layers[1];
            if (lastIframe) {
              lastIframe.destroy();
              layers.splice(1, 1);
            }
            const iframe = document.createElement('iframe');
            iframe.src = URL;
            iframe.onload = () => {
              layers.push(iframe);
            };
            iframe.onerror = err => {
              console.warn(err.stack);
            };
            
            setTimeout(_reload, Math.random() * 2000);
          };
          _reload();

          console.log('running!');
        });
      } else {
        console.log('no xr devices');
      }
    })();
  </script>
  </body>
</html>
